package com.agileboot.attendance.domain.rule.service.impl;

import com.agileboot.attendance.domain.rule.db.entity.AttendanceRule;
import com.agileboot.attendance.domain.rule.db.mapper.AttendanceRuleMapper;
import com.agileboot.attendance.domain.rule.dto.AttendanceRuleDTO;
import com.agileboot.attendance.domain.rule.dto.AttendanceRuleQueryDTO;
import com.agileboot.attendance.domain.rule.service.IAttendanceRuleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 考勤规则Service实现类
 *
 * @author ruoyi
 */
@Service
@Primary
public class AttendanceRuleServiceImpl extends ServiceImpl<AttendanceRuleMapper, AttendanceRule> implements IAttendanceRuleService {

    @Override
    public IPage<AttendanceRuleDTO> page(IPage<AttendanceRule> page, AttendanceRuleQueryDTO queryDTO) {
        LambdaQueryWrapper<AttendanceRule> wrapper = new LambdaQueryWrapper<>();

        // 规则名称模糊查询
        if (StringUtils.hasText(queryDTO.getRuleName())) {
            wrapper.like(AttendanceRule::getRuleName, queryDTO.getRuleName());
        }

        // 状态查询
        if (queryDTO.getStatus() != null) {
            wrapper.eq(AttendanceRule::getStatus, queryDTO.getStatus());
        }

        // 按创建时间降序排序
        wrapper.orderByDesc(AttendanceRule::getCreateTime);

        // 执行分页查询
        IPage<AttendanceRule> rulePage = this.page(page, wrapper);

        // 转换为DTO
        return rulePage.convert(rule -> {
            AttendanceRuleDTO dto = new AttendanceRuleDTO();
            BeanUtils.copyProperties(rule, dto);
            return dto;
        });
    }

    @Override
    public boolean add(AttendanceRuleDTO ruleDTO) {
        AttendanceRule rule = new AttendanceRule();
        BeanUtils.copyProperties(ruleDTO, rule);
        return this.save(rule);
    }

    @Override
    public boolean update(AttendanceRuleDTO ruleDTO) {
        AttendanceRule rule = new AttendanceRule();
        BeanUtils.copyProperties(ruleDTO, rule);
        return this.updateById(rule);
    }

    @Override
    public boolean delete(Long ruleId) {
        return this.removeById(ruleId);
    }

    @Override
    public AttendanceRuleDTO getInfo(Long ruleId) {
        AttendanceRule rule = this.getById(ruleId);
        if (rule == null) {
            return null;
        }
        AttendanceRuleDTO dto = new AttendanceRuleDTO();
        BeanUtils.copyProperties(rule, dto);
        return dto;
    }
}
